from flask import request, jsonify, Blueprint
from flask_jwt_extended import jwt_required, get_jwt_identity, verify_jwt_in_request, get_jwt_identity
from sqlalchemy import text

from flaskapp.util.Redprint import Redprint
from flaskapp.entity.Reserve import Reserve
from flaskapp.entity.Maintain import Maintain
from flaskapp.entity.Rent import Rent
from flaskapp.entity.User import User
from flaskapp.entity.House import House
from flaskapp.util.Sqlalchemy import db
from datetime import datetime
from flaskapp.util.jwt_optional_for_options import jwt_optional_for_options
from werkzeug.utils import secure_filename
import os

import json

api = Redprint('landlord')

UPLOAD_FOLDER = 'static/house-img'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@api.route('/house', methods=['POST', 'OPTIONS'])
@jwt_optional_for_options
def add_house():
    try:
        payload = request.jwt_payload
        landlord_id = payload['user_id']
        data = request.form
        required_fields = [
            'monthly_rent', 'rental_method', 'house_type',
            'floor_area', 'orientation', 'decoration',
            'district', 'address'
        ]
        for field in required_fields:
            if field not in data:
                return jsonify({'status': 400, 'message': f'缺少必填字段: {field}'}), 400
        photo_path = None
        if 'photo' in request.files:
            photo = request.files['photo']
            if photo.filename != '' and allowed_file(photo.filename):
                filename = secure_filename(photo.filename)
                photo_path = os.path.join(UPLOAD_FOLDER, filename)
                photo.save(photo_path)
                photo_url = f"/static/house-img/{filename}"
            else:
                photo_url = None
        new_house = House(
            monthly_rent=float(data['monthly_rent']),
            rental_method=data['rental_method'],
            house_type=data['house_type'],
            floor_area=float(data['floor_area']),
            orientation=data['orientation'],
            decoration=data['decoration'],
            district=data['district'],
            address=data['address'],
            landlord_id=landlord_id,
            description=data.get('description'),
            photo_url=photo_url,
            status='闲置'
        )
        try:
            db.session.add(new_house)
            db.session.commit()
            return jsonify({'status': 200, 'message': '房源信息添加成功', 'data': new_house.to_dict()})
        except Exception as e:
            db.session.rollback()
            return jsonify({'status': 500, 'message': f'数据库错误: {str(e)}'}), 500
    except Exception as e:
        return jsonify({'status': 500, 'message': f'服务器错误: {str(e)}'}), 500

# 获取自己的房源列表
@api.route('/my-houses', methods=['GET', 'OPTIONS'])
@jwt_optional_for_options
def get_my_houses():
    try:
        payload = request.jwt_payload
    except:
        return jsonify({
            "status": 401,
            "msg": "未授权的访问（JWT 验证失败）",
            "error": "Invalid token"
        }), 401
    landlord_id = payload['user_id']
    page1 = int(request.args.get('page', 1))
    per_page1 = int(request.args.get('per_page', 5))
    query = House.query.filter_by(landlord_id=landlord_id)
    total = query.count()
    houses = query.offset((page1 - 1) * per_page1).limit(per_page1).all()
    house_list = []
    import os
    for h in houses:
        d = h.to_dict()
        if d.get('photo_url'):
            d['photo_url'] = os.path.basename(d['photo_url'])
        # 如果房屋状态为“出租中”，则查询租客信息
        if h.status == '出租中':
            rent_record = Rent.query.filter_by(house_id=h.house_id).order_by(Rent.rent_date.desc()).first()
            if rent_record:
                tenant = User.query.filter_by(user_id=rent_record.tenant_id).first()
                if tenant:
                    d['tenant_name'] = tenant.account_name
                    d['tenant_id'] = tenant.user_id
                    d['tenant_phone'] = tenant.phone # 新增：获取租客电话
        house_list.append(d)
    total_pages = (total + per_page1 - 1) // per_page1
    return jsonify({
        "status": 200,
        "msg": "获取房东房源成功",
        "data": house_list,
        "pagination": {
            "total": total,
            "page": page1,
            "per_page": per_page1,
            "total_pages": total_pages
        }
    })

# 更新房源信息
@api.route('/my-houses/<int:house_id>', methods=['PUT', 'OPTIONS'])
@jwt_optional_for_options
def update_my_house(house_id):
    try:
        payload = request.jwt_payload
    except:
        return jsonify({
            "status": 401,
            "msg": "未授权的访问（JWT 验证失败）",
            "error": "Invalid token"
        }), 401
    landlord_id = payload['user_id']
    house = House.query.filter_by(house_id=house_id, landlord_id=landlord_id).first()
    if not house:
        return jsonify({
            "status": 404, 
            "msg": "房源不存在或无权修改"
            }), 404
    data = request.json
    for key in ['monthly_rent', 
    'rental_method',
     'house_type',
      'floor_area', 
      'orientation', 
      'decoration', 
      'district',
       'address',
        'description', 
        'status']:
        if key in data:
            setattr(house, key, data[key])
    db.session.commit()
    return jsonify({"status": 200, "msg": "房源信息修改成功", "data": house.to_dict()})

# 获取房东的预约反馈列表
@api.route('/appointments', methods=['GET', 'OPTIONS'])
@jwt_optional_for_options
def get_landlord_appointments():
    try:
        payload = request.jwt_payload
    except:
        return jsonify({
            "status": 401,
            "msg": "未授权的访问（JWT 验证失败）",
            "error": "Invalid token"
        }), 401
    landlord_id = payload['user_id']
    # current_user = get_jwt_identity()
    # landlord_id = current_user['user_id']

    # 获取查询参数
    status = request.args.get('status')
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)

    # 构建查询
    query = Reserve.query.filter_by(landlord_id=landlord_id)

    # 根据状态筛选
    if status:
        query = query.filter_by(status=status)

    # 按时间倒序排序
    query = query.order_by(Reserve.created_at.desc())

    # 分页
    total = query.count()
    appointments = query.limit(per_page).offset((page - 1) * per_page).all()

    # 构建响应数据
    result = []
    for appointment in appointments:
        # 获取访客信息
        visitor = User.query.filter_by(user_id=appointment.visitor_id).first()
        visitor_name = visitor.account_name if visitor else "未知用户"

        # 获取房屋信息
        house = House.query.filter_by(house_id=appointment.house_id).first()
        house_address = house.address if house else "未知房屋"

        result.append({
            'reserve_id': appointment.reserve_id,
            'visitor_id': appointment.visitor_id,
            'visitor_name': visitor_name,
            'house_id': appointment.house_id,
            'house_address': house_address,
            'appointment_time': appointment.appointment_time.isoformat(),
            'status': appointment.status,
            'created_at': appointment.created_at.isoformat() if appointment.created_at else None
        })

    return jsonify({
        'status': 200,
        'msg': '获取预约列表成功',
        'data': {
            'appointments': result,
            'total': total,
            'page': page,
            'per_page': per_page
        }
    })


# 更新预约状态
@api.route('/appointments/<int:reserve_id>/status', methods=['PUT', 'OPTIONS'])
@jwt_optional_for_options
def update_appointment_status(reserve_id):
    # current_user = get_jwt_identity()
    # landlord_id = current_user['user_id']
    try:
        payload = request.jwt_payload
    except:
        return jsonify({
            "status": 401,
            "msg": "未授权的访问（JWT 验证失败）",
            "error": "Invalid token"
        }), 401
    landlord_id = payload['user_id']
    # 获取请求数据
    data = request.json
    new_status = data.get('status')

    if not new_status or new_status not in ['待确认', '已确认', '已取消']:
        return jsonify({
            'status': 400,
            'msg': '无效的状态值'
        })

    # 查找预约
    appointment = Reserve.query.filter_by(reserve_id=reserve_id, landlord_id=landlord_id).first()

    if not appointment:
        return jsonify({
            'status': 404,
            'msg': '预约不存在或您无权修改'
        })

    # 更新状态
    appointment.status = new_status
    db.session.commit()

    return jsonify({
        'status': 200,
        'msg': '预约状态更新成功',
        'data': {
            'reserve_id': appointment.reserve_id,
            'status': appointment.status
        }
    })


# 获取房东的维修反馈列表
@api.route('/maintenance', methods=['GET', 'OPTIONS'])
@jwt_optional_for_options
def get_landlord_maintenance():
    try:
        payload = request.jwt_payload
    except:
        return jsonify({
            "status": 401,
            "msg": "未授权的访问（JWT 验证失败）",
            "error": "Invalid token"
        }), 401
    landlord_id = payload['user_id']
    # current_user = get_jwt_identity()
    # landlord_id = current_user['user_id']

    # 获取查询参数
    status = request.args.get('status')
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    # status = 1
    # page = 1
    # per_page = 1
    # 构建查询
    query = Maintain.query.filter_by(landlord_id=landlord_id)

    # 根据状态筛选
    if status:
        query = query.filter_by(status=status)

    # 按时间倒序排序
    query = query.order_by(Maintain.submitted_at.desc())

    # 分页
    total = query.count()
    maintenance_requests = query.limit(per_page).offset((page - 1) * per_page).all()

    # 构建响应数据
    result = []
    for request1 in maintenance_requests:
        # 获取租户信息
        tenant = User.query.filter_by(user_id=request1.tenant_id).first()
        tenant_name = tenant.account_name if tenant else "未知用户"

        # 获取房屋信息
        house = House.query.filter_by(house_id=request1.house_id).first()
        house_address = house.address if house else "未知房屋"

        result.append({
            'request_id': request1.request_id,
            'tenant_id': request1.tenant_id,
            'tenant_name': tenant_name,
            'house_id': request1.house_id,
            'house_address': house_address,
            'content': request1.content,
            'submitted_at': request1.submitted_at.isoformat() if request1.submitted_at else None,
            'status': request1.status,
            'processed_at': request1.processed_at.isoformat() if request1.processed_at else None,
            'result_notes': request1.result_notes
        })

    return jsonify({
        'status': 200,
        'msg': '获取维修请求列表成功',
        'data': {
            'maintenance_requests': result,
            'total': total,
            'page': page,
            'per_page': per_page
        }
    })


# 更新维修请求状态和添加处理结果
@api.route('/maintenance/<int:request_id>', methods=['PUT', 'OPTIONS'])
@jwt_optional_for_options
def update_maintenance_request(request_id):
    # current_user = get_jwt_identity()
    # landlord_id = current_user['user_id']
    try:
        payload = request.jwt_payload
    except:
        return jsonify({
            "status": 401,
            "msg": "未授权的访问（JWT 验证失败）",
            "error": "Invalid token"
        }), 401
    landlord_id = payload['user_id']
    # 获取请求数据
    data = request.json
    new_status = data.get('status')
    result_notes = data.get('result_notes')

    if not new_status or new_status not in ['待处理', '处理中', '已完成', '已取消']:
        return jsonify({
            'status': 400,
            'msg': '无效的状态值'
        })

    # 查找维修请求
    maintenance_request = Maintain.query.filter_by(request_id=request_id, landlord_id=landlord_id).first()

    if not maintenance_request:
        return jsonify({
            'status': 404,
            'msg': '维修请求不存在或您无权修改'
        })

    # 更新状态和处理结果
    maintenance_request.status = new_status

    if result_notes:
        maintenance_request.result_notes = result_notes

    # 如果状态变为已完成，更新处理时间
    if new_status == '已完成':
        maintenance_request.processed_at = datetime.now()

    db.session.commit()

    return jsonify({
        'status': 200,
        'msg': '维修请求更新成功',
        'data': {
            'request_id': maintenance_request.request_id,
            'status': maintenance_request.status,
            'processed_at': maintenance_request.processed_at.isoformat() if maintenance_request.processed_at else None,
            'result_notes': maintenance_request.result_notes
        }
    })


# 获取房东的租金收入概览
@api.route('/income/overview', methods=['GET', 'OPTIONS'])
@jwt_optional_for_options
def get_landlord_income_overview():
    # current_user = get_jwt_identity()
    # landlord_id = current_user['user_id']
    try:
        payload = request.jwt_payload
    except:
        return jsonify({
            "status": 401,
            "msg": "未授权的访问（JWT 验证失败）",
            "error": "Invalid token"
        }), 401
    landlord_id = payload['user_id']
    # 执行原生SQL查询获取总收入概览
    # sql = """
    # SELECT
    #     u.user_id AS landlord_id,
    #     u.account_name,
    #     COALESCE(SUM(r.amount), 0) AS total_income,
    #     COUNT(r.rent_id) AS total_rents
    # FROM user u
    # LEFT JOIN rent r ON u.user_id = r.landlord_id
    # WHERE u.user_id = :landlord_id
    # GROUP BY u.user_id
    # """
    sql = text("""
        SELECT
            u.user_id AS landlord_id,
            u.account_name,
            COALESCE(SUM(r.amount), 0) AS total_income,
            COUNT(r.rent_id) AS total_rents
        FROM user u
        LEFT JOIN rent r ON u.user_id = r.landlord_id
        WHERE u.user_id = :landlord_id
        GROUP BY u.user_id
        """)
    result = db.session.execute(sql, {'landlord_id': landlord_id}).fetchone()

    if not result:
        return jsonify({
            'status': 200,
            'msg': '获取收入概览成功',
            'data': {
                'landlord_id': landlord_id,
                'account_name': User.query.get(landlord_id).account_name,
                'total_income': 0,
                'total_rents': 0
            }
        })

    return jsonify({
        'status': 200,
        'msg': '获取收入概览成功',
        'data': {
            'landlord_id': result[0],
            'account_name': result[1],
            'total_income': float(result[2]) if result[2] else 0,
            'total_rents': result[3]
        }
    })


# 获取房东的房屋收入详情
@api.route('/income/details', methods=['GET', 'OPTIONS'])
@jwt_optional_for_options
def get_landlord_income_details():
    # current_user = get_jwt_identity()
    # landlord_id = current_user['user_id']
    try:
        payload = request.jwt_payload
    except:
        return jsonify({
            "status": 401,
            "msg": "未授权的访问（JWT 验证失败）",
            "error": "Invalid token"
        }), 401
    landlord_id = payload['user_id']
    # 获取查询参数
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)

    # 执行原生SQL查询获取房屋收入详情
    # sql = """
    # SELECT
    #     h.house_id,
    #     h.address,
    #     h.monthly_rent,
    #     r.rent_id,
    #     r.start_date,
    #     r.end_date,
    #     r.amount,
    #     u.account_name AS tenant_name,
    #     u.user_id AS tenant_id
    # FROM house h
    # LEFT JOIN rent r ON h.house_id = r.house_id
    # LEFT JOIN user u ON r.tenant_id = u.user_id
    # WHERE h.landlord_id = :landlord_id
    # ORDER BY r.start_date DESC
    # LIMIT :limit OFFSET :offset
    # """
    #
    # # 计算总数的SQL
    # count_sql = """
    # SELECT COUNT(*)
    # FROM house h
    # LEFT JOIN rent r ON h.house_id = r.house_id
    # WHERE h.landlord_id = :landlord_id
    # """
    sql = text("""
        SELECT
            h.house_id,
            h.address,
            h.monthly_rent,
            r.rent_id,
            r.start_date,
            r.end_date,
            r.amount,
            u.account_name AS tenant_name,
            u.user_id AS tenant_id
        FROM house h
        LEFT JOIN rent r ON h.house_id = r.house_id
        LEFT JOIN user u ON r.tenant_id = u.user_id
        WHERE h.landlord_id = :landlord_id
        ORDER BY r.start_date DESC
        LIMIT :limit OFFSET :offset
        """)

    # 计算总数的SQL
    count_sql = text("""
        SELECT COUNT(*)
        FROM house h
        LEFT JOIN rent r ON h.house_id = r.house_id
        WHERE h.landlord_id = :landlord_id
        """)
    # 执行查询
    results = db.session.execute(sql, {
        'landlord_id': landlord_id,
        'limit': per_page,
        'offset': (page - 1) * per_page
    }).fetchall()

    # 获取总数
    total = db.session.execute(count_sql, {'landlord_id': landlord_id}).scalar()

    # 构建响应数据
    income_details = []
    for row in results:
        if row[3]:  # 如果有租金记录
            income_details.append({
                'house_id': row[0],
                'house_address': row[1],
                'monthly_rent': float(row[2]) if row[2] else 0,
                'rent_id': row[3],
                'start_date': row[4].isoformat() if row[4] else None,
                'end_date': row[5].isoformat() if row[5] else None,
                'amount': float(row[6]) if row[6] else 0,
                'tenant_name': row[7],
                'tenant_id': row[8]
            })
        else:  # 如果没有租金记录，只显示房屋信息
            income_details.append({
                'house_id': row[0],
                'house_address': row[1],
                'monthly_rent': float(row[2]) if row[2] else 0,
                'rent_id': None,
                'start_date': None,
                'end_date': None,
                'amount': 0,
                'tenant_name': None,
                'tenant_id': None
            })

    return jsonify({
        'status': 200,
        'msg': '获取收入详情成功',
        'data': {
            'income_details': income_details,
            'total': total,
            'page': page,
            'per_page': per_page
        }
    })


